package psnl.bingo.bgtool.framework.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import psnl.bingo.bgtool.model.constant.ConstSys;
import psnl.bingo.bgtool.model.dto.UserInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfo user = (UserInfo) request.getSession().getAttribute("user");
        if(null == user) {
            request.setAttribute("msg", "信息已过期，请重新登录");
            request.getRequestDispatcher("/loginPage").forward(request, response);
            return false;
        }else if(!ConstSys.users.containsKey(user.getName())
                || !ConstSys.users.get(user.getName()).getPassword().equals(user.getPassword())) {
            request.setAttribute("username", user.getName());
            request.setAttribute("password", user.getPassword());
            request.setAttribute("msg", "用户未登录，或登录信息已过期");
            request.getRequestDispatcher("/login").forward(request, response);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
